package cn.whdream.datastructure.stack;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Stack;

/**
 * 
 * @author admin
 * 逆波兰表达式 后缀表达式
 */
public class PolandNotation {
	public static void main(String[] args) {
		String suffixExpression = "30 4 + 5 * 6 - ";
		String[] temp = suffixExpression.split(" ");
		List<String> list = new ArrayList<>(Arrays.asList(temp));
		
		int res = calculateExpression(list);
		System.out.printf(suffixExpression +"= %d",res);
	}

	private static int calculateExpression(List<String> list) {
		Stack<Integer> stack = new Stack<>();
		for(String s:list) {
			if (s.matches("\\d+")) {
				stack.push(Integer.parseInt(s));
			}else {
				int num1 = stack.pop();
				int num2 = stack.pop();
				int res = calculate(num1, num2, s.charAt(0));
				stack.push(res);
			}
		}
		return stack.pop();
	}
	
	private static int calculate(int num1, int num2, int oper) {
		switch (oper) {
		case '+':
			return num1 + num2;
		case '-':
			return num2 - num1;
		case '*':
			return num1 * num2;
		case '/':
			return num2 / num1;	
		default:
			return 0;
		}
	
	}
}
